package com.winit.openapi.mms.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.Searchable;
import com.winit.common.spi.context.CommandContext;
import com.winit.mms.spi.v2.item.vo.PageVo;
import com.winit.mms.spi.v2.mt.ItemMtTaskService;
import com.winit.mms.spi.v2.mt.command.ImportItemMtTaskCommand;
import com.winit.mms.spi.v2.mt.command.PageItemMtEntryCommand;
import com.winit.mms.spi.v2.mt.command.QueryItemMtEntryDetailCommand;
import com.winit.mms.spi.v2.mt.command.RegisterItemShortcutCommand;
import com.winit.mms.spi.v2.mt.vo.ImportItemMtTaskResult;
import com.winit.mms.spi.v2.mt.vo.ItemMtEntryDetailVo;
import com.winit.mms.spi.v2.mt.vo.PageItemMtEntityVo;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.ums.spi.UmsCustomerService;
import com.winit.ums.spi.commnad.customer.QueryCompanylCommand;
import com.winit.ums.spi.vo.CustomerInfoVO;

/**
 * 商品Controller
 * 
 * @author qibin.tang
 */
@Controller
@RequestMapping(value = "/mms/itemmttask")
public class ItemMtTaskController extends BaseController {

	/**
	 * 维护任务
	 */
   @Resource
   private ItemMtTaskService		itemMtTaskService;
   
   /**
    * ums客户信息
    */
   @Resource
   private UmsCustomerService umsCustomerService;
   
    /**
     * 卖家网站导入产品
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/importItemMtTask")
    public String importItemMtTask(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	ImportItemMtTaskCommand command = JSON.parseObject(requestMsg.getData().toString(),
    			ImportItemMtTaskCommand.class);
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        command.setCustomerName(customer.getName());
        //command.setType("sellerImport");
        ImportItemMtTaskResult result = itemMtTaskService.importItemMtTask(command);
        responseMsg.setData(result);
        return SUCCESS;
    }
    
    /**
     * 卖家网站维护修改
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/sellerMtTaskModify")
    public String sellerMtTaskModify(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        ImportItemMtTaskCommand command = JSON.parseObject(requestMsg.getData().toString(),
                ImportItemMtTaskCommand.class);
        command.setCtx(CommandContext.getContext());
        command.setType("sellerModify");
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        command.setCustomerName(customer.getName());
        ImportItemMtTaskResult result = itemMtTaskService.importItemMtTask(command);
        responseMsg.setData(result);
        return SUCCESS;
    }

    /**
     * 卖家网站快捷注册
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/registerItemShortcut")
    public String registerItemShortcut(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	
        RegisterItemShortcutCommand command = JSON.parseObject(requestMsg.getData().toString(),
            RegisterItemShortcutCommand.class);
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        command.setCustomerName(customer.getName());
        String result = itemMtTaskService.registerItemShortcut(command);
        responseMsg.setData(result);
        return SUCCESS;
    }

    
    /**
     * 
     * MMS3.0维护商品列表
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryItemMtEntitys")
    public String queryItemMtEntitys(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        PageItemMtEntryCommand command = JSON.parseObject(requestMsg.getData().toString(),PageItemMtEntryCommand.class);
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        Page<PageItemMtEntityVo> page = itemMtTaskService.pageItemMtEntrys(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.content);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }
    
    @RequestMapping(value = "/queryItemMtEntryDetail")
    public String queryItemMtEntryDetail(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        QueryItemMtEntryDetailCommand command = JSON.parseObject(requestMsg.getData().toString(),QueryItemMtEntryDetailCommand.class);
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        ItemMtEntryDetailVo vo = itemMtTaskService.queryItemMtEntryDetail(command);
        responseMsg.setData(vo);
        return SUCCESS;
    }

    /**
     * MMS3.0分页查询维护商品列表:openapi使用
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryItemMtEntitysForOpenAPI")
    public String queryItemMtEntitysForOpenAPI(@ModelAttribute RequestMsg requestMsg,
                                               @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            PageItemMtEntryCommand command = validateAndBuildCommand(json);
            command.setCtx(CommandContext.getContext());
            QueryCompanylCommand userCommand = new QueryCompanylCommand();
            userCommand.setEmail(CommandContext.getContext().getUsername());
            // 获取客户编码
            CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
            if (customer == null || customer.getCode() == null) {
                throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
            }
            command.setCustomerCode(customer.getCode());
            Map<String, Object> data = new HashMap<String, Object>();
            Page<PageItemMtEntityVo> page = itemMtTaskService.pageItemMtEntrys(command);
            if (page == null || page.getContent().isEmpty()) {
                Map<String, Object> pageMap = new HashMap<String, Object>();
                List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                pageMap.put("pageNo", command.getPageVo().getPageNo());
                pageMap.put("pageSize", command.getPageVo().getPageSize());
                pageMap.put("totalCount", 0);
                data.put("pageParams", pageMap);

                data.put("list", list);
            } else {
                data = this.getPageParams(page);
                data.put("list", buildResult(page.getContent()));
            }

            responseMsg.setData(data);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    private List<Map<String, Object>> buildResult(List<PageItemMtEntityVo> content) {
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        if (content.isEmpty()) {
            return data;
        }
        for (PageItemMtEntityVo vo : content) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("skuCode", vo.getSkuCode());
            map.put("cnName", vo.getCnName());
            map.put("englishName", vo.getName());
            map.put("specification", vo.getSpecification());
            map.put("status", vo.getStatus());
            // 待维护:DR、已发布:PD、维护完成:CO、维护终止：VO、退回:BK'
            String statusName = null;
            if ("DR".equals(vo.getStatus())) {
                statusName = "待维护";
            } else if ("PD".equals(vo.getStatus())) {
                statusName = "已发布";
            } else if ("PC".equals(vo.getStatus())) {
                statusName = "部分完成";
            } else if ("CO".equals(vo.getStatus())) {
                statusName = "维护完成";
            } else if ("VO".equals(vo.getStatus())) {
                statusName = "维护终止";
            } else if ("BK".equals(vo.getStatus())) {
                statusName = "退回";
            } else {
                statusName = "状态未知";
            }

            map.put("statusName", statusName);
            map.put("description", vo.getDescription());
            map.put("exportCountryCode", vo.getExportCountryCode());
            map.put("importStartDate", vo.getCreated());
            map.put("returnReason", vo.getMtBackReason() == null ? StringUtils.EMPTY : vo.getMtBackReason());
            map.put("maintainTime", vo.getMtTime() == null ? StringUtils.EMPTY : vo.getMtTime());

            data.add(map);

        }

        return data;

    }

    private PageItemMtEntryCommand validateAndBuildCommand(JSONObject json) {
        PageItemMtEntryCommand command = new PageItemMtEntryCommand();
        ValidateUtil.validNotNull(json, "importCountryCode");
        command.setImportCountryCode(json.getString("importCountryCode"));
        if (json.containsKey("importStartDate")) {
            ValidateUtil.validDateString(json, "importStartDate", "yyyy-MM-dd HH:mm:ss");
            command.setImportStartTime(json.getString("importStartDate"));
        }
        if (json.containsKey("importEndDate")) {
            ValidateUtil.validDateString(json, "importEndDate", "yyyy-MM-dd HH:mm:ss");
            command.setImportEndTime(json.getString("importEndDate"));
        }
        if (StringUtils.isNotBlank(command.getImportStartTime()) && StringUtils.isNotBlank(command.getImportEndTime())) {
            ValidateUtil.validDateBefore(json, "importStartDate", "importEndDate");
        }

        if (json.containsKey("skuCode")) {
            command.setSkuCode(json.getString("skuCode"));
        }
        if (json.containsKey("englishName")) {
            command.setName(json.getString("englishName"));
        }
        // 待维护:DR、已发布:PD、维护完成:CO、维护终止：VO、退回:BK',
        if (json.containsKey("status")) {
            ValidateUtil.validByRegex(json, "status", "(DR|PD|VO|BK|CO)");
            command.setStatus(json.getString("status"));
        }

        Searchable searchable = buildSearchablePageParams(json);
        PageVo pageVo = new PageVo();
        pageVo.setPageNo(searchable.getPage().getPageNumber());
        pageVo.setPageSize(searchable.getPage().getPageSize());
        command.setPageVo(pageVo);

        return command;
    }
}
